<template>
<div id="app">
    <el-form :inline="true" :model="formSelect" class="demo-form-inline">
        <el-form-item label="选择学期" prop="teamValue">
            <el-select size="small" v-model="formSelect.team" clearable @change="teamChange(formSelect.team)">
                <el-option v-for="item in teamData" :key="item.termid" :label="item.termName" :value="item.termid"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="选择周次" prop="weekValue">
            <el-select size="small" v-model="formSelect.week" clearable @change="weekChange(formSelect.week)">
                <el-option v-for="item in weekData" :key="item.weekId" :label="'第' + item.week + '周'" :value="item.week"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="选择楼栋" prop="buildingName">
            <el-select size="small" v-model="formSelect.buildingName" clearable @change="buildChange(formSelect.buildingName)">
                <el-option v-for="item in buildData" :key="item.number" :label="item.name" :value="item.name"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item>
            <el-button size="small" circle icon="el-icon-refresh" @click="resetSearch"></el-button>
            <el-button size="small" @click="getDataList()" type="primary" icon="el-icon-search">查询</el-button>
            <el-button size="small" @click="uploadExcel" type="primary">
                <input type="file" name id="file" style="display:none" />
                导入Excel
            </el-button>
            <el-button size="small" type="success" @click="download">导出Excel</el-button>
            <el-button size="small" type="success" @click="shuttering">下载模板</el-button>
        </el-form-item>
    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle" style="width: 100%;">
        <el-table-column prop="termName" header-align="center" align="center" label="学期" width="300px"></el-table-column>
        <el-table-column prop="week" header-align="center" align="center" width="80" label="周次"></el-table-column>
        <el-table-column prop="teacherName" header-align="center" align="center" label="值班辅导员"></el-table-column>
        <el-table-column prop="buildingName" header-align="center" align="center" label="值班地点"></el-table-column>

        <el-table-column header-align="center" align="center" label="操作" fixed="right" width="200px">
            <template slot-scope="scope">
                <el-button type="primary" size="small" @click="write(scope.row)">查看详情列表</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination class="pagination" background @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" layout="total, sizes, prev, pager, next, jumper"></el-pagination>

    <el-drawer title="填写结果" :visible.sync="drawer" direction="rtl" size="40%" ref="drawer" @close="clearDuty">
        <div class="demo-drawer__content">
            <el-form :model="detailForm" label-position="right">
                <el-form-item label="值班日期" label-width="120px">
                    <el-date-picker v-model="detailForm.dutyDate" :disabled="upOrSave" align="right" type="date" placeholder="选择值班日期" :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="值班教师" label-width="120px">
                    <el-autocomplete class="input-new-tag" v-model="detailForm.teacherName" :fetch-suggestions="querySearchAsync" ref="saveTagInput" :trigger-on-focus="true" style="width: 220px;"></el-autocomplete>
                </el-form-item>
                <!--          disabled-->
                <el-form-item label="备注" label-width="120px">
                    <el-input v-model="detailForm.remark" style="width: 220px"></el-input>
                </el-form-item>
                <el-form-item style="margin-left: 55px; margin-right: 60px;">
                    <el-button size="small" @click="cancelFormSimple">取 消</el-button>
                    <el-button size="small" type="primary" v-show="commitType" @click="upOrSave ? updateSpotPlan() : saveDuty()">提交</el-button>
                </el-form-item>
            </el-form>
        </div>
    </el-drawer>

    <!-- 值班分配 -->
    <el-drawer title="值班分配" :visible.sync="drawerplus" direction="rtl" size="80%" @close="drawerclose" ref="drawerplus">
        <div class="demo-drawer__content">
            <el-button type="success" size="small" style="margin: 0 0 20px 20px" @click="addDutyData">新增</el-button>
            <el-table :data="deatilDataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle" style="width: 100%;">
                <el-table-column prop="dutyDate" header-align="center" align="center" label="值班日期"></el-table-column>
                <el-table-column prop="teacherName" header-align="center" align="center" label="值班教师"></el-table-column>
                <el-table-column prop="remark" header-align="center" align="center" label="备注"></el-table-column>
                <el-table-column header-align="center" align="center" label="操作" fixed="right" width="270px">
                    <template slot-scope="scope">
                        <el-button type="danger" size="small" @click="delDuty(scope.row)">删除</el-button>
                        <el-button type="primary" size="small" @click="updateDetail(scope.row)">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </el-drawer>
</div>
</template>

<script>
import {
    getDutyList,
    getWeekList,
    getTermList,
    getBuildList,
    addDutyDetails,
    updataDutyDetails,
    deleteDutyDetails,
    excel,
    addExceldata,
    getExcel,
    downloadWorkShuttering,
    getDetailList,
    getWeekTime,
} from '../../api/src/DutyDetails/DutyDetails'
import {
    getTeacherListByLikeName
} from '../../api/src/check/a7sCheck'

export default {
    name: 'DutyDetails',
    data() {
        return {
            upOrSave: false,
            formSelect: {
                buildingName: '',
                week: '',
                termid: '',
            },
            form: {
                id: '',
                buildingName: '',
                remark: '',
                week: '',
                termName: '',
                teacherName: '',
                dutyOneName: '',
                adviserOneNumber: '',
                dutyTwoName: '',
                adviserTwoNumber: '',
                instructorName: '',
                counselorNumber: '',
                leaderName: '',
                leaderNumber: '',
                middleName: '',
                middleNumber: '',
                plan: '',
                summary: '',
                termid: '',
                weekDayId: '',
            },
            detailForm: {
                id: '',
                teacherName: '',
                remark: '',
                dutyDate: '',
            },

            teamData: [],
            weekData: [],
            buildData: [],
            dataList: [],
            deatilDataList: [],
            pageIndex: 1,
            pageSize: 10,
            totalPage: 0,
            dataListLoading: false,
            dataListSelections: [],
            dynamicTags: [],
            commitType: true,
            id: '',
            excelData: [],
            drawer: false,
            drawerplus: false,

            week: '',
            buildingId: '',
            termId: '',

            // 周次开始时间，结束时间
            weekStart: '',
            weekEnd: '',
            pickerOptions: {
                disabledDate: time => {
                    let start = this.weekStart
                    start = start.replace(new RegExp('-', 'gm'), '/')
                    const startTime = new Date(start).getTime()

                    let end = this.weekEnd
                    end = end.replace(new RegExp('-', 'gm'), '/')
                    const endTime = new Date(end).getTime()

                    return time.getTime() < startTime || time.getTime() > endTime
                },
            },
        }
    },
    created() {
        this.getDataList()
    },
    methods: {
        // 导入Excel数据
        uploadExcel() {
            const file = document.getElementById('file')
            file.click()
            file.onchange = () => {
                if (!this.checkType(file.files[0])) {
                    this.$message.error(
                        '文件：' + file.files[0].name + ' 文件类型错误，请使用Excel文件'
                    )
                    return false
                }
                excel(file.files[0]).then(res => {
                    if (!res) {
                        this.$message.error('Excel内容格式错误！请使用正确格式。')
                    }
                    this.processExceldata(res)
                })
            }
        },
        // 检测文件类型
        checkType(file) {
            const fileExt = file.name
                .split('.')
                .pop()
                .toLocaleLowerCase()
            const extArr = ['xlsx', 'xls', 'csv']
            return extArr.includes(fileExt)
        },
        // 格式Excel数据
        processExceldata(data) {
            for (let index = 0; index < data.length; index++) {
                const ele = data[index]
                const celldata = {
                    teacherName: ele.辅导员,
                    buildingName: ele.值班地点,
                    remark: ele.备注,
                    interval: ele.值班日期,
                    week: ele.值班周次,
                }
                this.excelData.push(celldata)
            }
            addExceldata(this.excelData).then(res => {
                this.excelData = []
                this.getDataList()
            })
        },
        // 获取周次范围
        async getWeekTimeArea() {
            const data = await getWeekTime(this.termId, this.week)
            this.weekStart = data.data.startDay
            this.weekEnd = data.data.endDay
        },
        // 清空搜索
        resetSearch() {
            this.formSelect = {
                buildingName: '',
                week: '',
                termid: '',
            }
            this.getDataList()
        },
        // 导出Excel数据
        download() {
            getExcel()
        },
        //导出模板
        shuttering() {
            downloadWorkShuttering()
        },
        // 删除值班
        delDuty(duty) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                .then(async () => {
                    const data = await deleteDutyDetails({
                        data: [duty.id],
                    })
                    this.$message.success(data)
                    let parameter

                    parameter = ''
                    parameter += '?buildingId=' + this.buildingId
                    parameter += '&termId=' + this.termId
                    parameter += '&week=' + this.week
                    getDetailList(parameter).then(res => {
                        this.deatilDataList = res
                        this.dataListLoading = false
                    })
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除',
                    })
                })
        },

        async getDetailDataList() {},
        // 获取数据列表
        async getDataList() {
            this.dataListLoading = true
            this.dataList = []
            let parameter

            parameter =
                '?currentPage=' + this.pageIndex + '&pageSize=' + this.pageSize

            if (this.formSelect.buildingName.length > 0) {
                parameter += '&buildingName=' + this.formSelect.buildingName
            }
            if (this.formSelect.termid > 0) {
                parameter += '&termName=' + this.formSelect.termid
            }
            if (this.formSelect.week > 0) {
                parameter += '&week=' + this.formSelect.week
            }

            await getDutyList(parameter).then(res => {
                if (res.records === 0) {
                    this.dataList = []
                    this.totalPage = 0
                } else {
                    this.dataList = res.records
                    this.totalPage = res.total
                }

                this.dataListLoading = false
            })

            getBuildList().then(res => {
                this.buildData = res
            })

            getTermList().then(res => {
                this.teamData = res
            })
        },
        // 新增值班未提交操作
        async addDutyData() {
            this.drawer = true
            this.upOrSave = false
            this.getWeekTimeArea()
        },
        // 新增值班提交
        async saveDuty() {
            const duty = {
                termId: this.termId,
                week: this.week,
                buildingId: this.buildingId,
                dutyDate: this.detailForm.dutyDate,
                remark: this.detailForm.remark,
                teacherName: this.detailForm.teacherName,
            }
            const data = await addDutyDetails(duty)
            this.$message.success(data)
            let parameter

            parameter = ''
            parameter += '?buildingId=' + this.buildingId
            parameter += '&termId=' + this.termId
            parameter += '&week=' + this.week
            getDetailList(parameter).then(res => {
                console.log('roleManagement::::::::>>>>', res)
                this.deatilDataList = res
                this.dataListLoading = false
            })
            this.drawer = false
        },
        // 清除分配表单内容
        clearDuty() {
            this.detailForm = {
                id: '',
                teacherName: '',
                remark: '',
                dutyDate: '',
            }
        },
        // 每页数
        sizeChangeHandle(val) {
            this.pageSize = val
            this.pageIndex = 1
            this.getDataList()
        },
        // 当前页
        currentChangeHandle(val) {
            this.pageIndex = val
            this.getDataList()
        },
        // 多选
        selectionChangeHandle(val) {
            this.dataListSelections = val
        },

        // 教师查找
        querySearchAsync(queryString, callback) {
            var list = [{}]
            var restaurants = this.restaurants

            getTeacherListByLikeName(queryString).then(res => {
                //在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
                for (let i of res) {
                    i.value = i.userName //将想要展示的数据作为value
                }
                list = res
                callback(list)
            })
        },

        handleSelect(item) {
            this.inputValue = ''
            this.dynamicTags.push(item)
        },
        write(row) {
            this.week = row.week
            this.buildingId = row.buildingId
            this.termId = row.termId

            this.deatilDataList = []
            let parameter

            parameter = ''
            parameter += '?buildingId=' + row.buildingId
            parameter += '&termId=' + row.termId
            parameter += '&week=' + row.week
            getDetailList(parameter).then(res => {
                this.deatilDataList = res
                this.dataListLoading = false
            })
            this.drawerplus = true
        },

        updateDetail(row) {
            this.upOrSave = true;
            (this.detailForm.id = row.id),
            (this.detailForm.teacherName = row.teacherName),
            (this.detailForm.remark = row.remark),
            (this.detailForm.dutyDate = row.dutyDate)
            this.drawer = true
        },

        async updateSpotPlan() {
            await updataDutyDetails(
                this.detailForm.id,
                this.detailForm.remark,
                this.detailForm.teacherName
            ).then(res => {
                this.$message.success(res)
            })
            let parameter

            parameter = ''
            parameter += '?buildingId=' + this.buildingId
            parameter += '&termId=' + this.termId
            parameter += '&week=' + this.week
            getDetailList(parameter).then(res => {
                this.deatilDataList = res
                this.dataListLoading = false
            })
            this.drawer = false
        },

        cancelForm() {
            (this.drawer = false), (this.drawerplus = false)
        },

        cancelFormSimple() {
            this.drawer = false
        },

        drawerclose() {
            this.getDataList()
            this.drawerplus = false
        },

        // 删除
        async deleteHandle(id) {
            var ids = id ?
                [id] :
                this.dataListSelections.map(item => {
                    return item.id
                })

            ids.push(id)
            await this.$confirm(
                    `确定进行[${id ? '删除' : '批量删除'}]操作?`,
                    '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                )
                .then(() => {
                    deleteDutyDetails(ids).then(res => {
                        this.$message({
                            message: '删除成功!',
                            duration: 1500,
                            type: 'success',
                        })
                    })
                })
                .catch(() => {})
            this.dataListSelections = []
            setTimeout(this.getDataList, 800)
        },
        // 学期进行选择
        teamChange(value) {
            this.formSelect.termid = value
            if (value.length == 0) {
                return
            }
            getWeekList(value).then(res => {
                this.weekData = res
            })
        },
        // 周次进行选择
        weekChange(value) {
            this.formSelect.week = value
            for (var i = 0; i < this.weekData.length; i++) {
                if (this.weekData[i].week == value) {
                    this.form.weekDayId = this.weekData[i].weekId
                }
            }
        },

        buildChange(value) {
            this.formSelect.buildingName = value
        },
    },
}
</script>

<style>
.el-pagination {
    display: flex;
    white-space: nowrap;
    padding: 20px 5px;
    color: #303133;
}
</style>
